package vn.ttpcode.com.sample.keyboard;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.RelativeLayout;

public class KeyboardWrapperView extends RelativeLayout{
	
	private static final String TAG = "ttpcode";
	private static KeyboardListener impl;
	private int tmpNewSpec;
	private boolean hasShown;
	
	public KeyboardWrapperView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
		Log.e(TAG, "onMeasure - onMeasure");
	    if (impl != null) {
	    	int newSpec = MeasureSpec.getSize(heightMeasureSpec); 
	        int oldSpec = getMeasuredHeight();
	        
	        Log.d(TAG, "oldSpec: " + oldSpec + " => newSpec: " + newSpec);
	        
	        if(0 == oldSpec){
	        	tmpNewSpec = newSpec;
	        }else{
	        	if(tmpNewSpec == newSpec){
	        		Log.d(TAG, "keyboard HIDDEN");
	        		hasShown = false;
	        	}else{
	        		Log.d(TAG, "keyboard SHOWN");
	        		hasShown = true;
	        	}
	        }
	    }
	    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}
	
	@Override
	public boolean dispatchKeyEventPreIme(KeyEvent event) {
		// TODO Auto-generated method stub
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
	        if (event.getAction() == KeyEvent.ACTION_DOWN
	                && event.getRepeatCount() == 0) {
	        	Log.e(TAG, "dispatchKeyEventPreIme - dispatchKeyEventPreIme");
	        	
	        	//Call back when keyboard shown 
	        	impl.onKeyboardStatusChanged(event, hasShown);
	        }
		}
		return super.dispatchKeyEventPreIme(event);
	}
    
	
	/**
	 * @param progress the progress to set
	 */
	public static void setImplements(KeyboardListener impl) {
		KeyboardWrapperView.impl = impl;
	}
	
	/**
	 * Create progress listener interface
	 */
	public interface KeyboardListener{
		public void onKeyboardStatusChanged(KeyEvent event, boolean hasShown);
	}

}
